<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智慧教室监控系统 By:刘佳雨</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    <!-- MQTT库 -->
    <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        success: '#00B42A',
                        dark: '#1D2129',
                        light: '#F2F3F5'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-shadow {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            }
            .animate-pulse-slow {
                animation: pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite;
            }
            .animate-alarm {
                animation: alarm 1s cubic-bezier(0.4, 0, 0.6, 1) infinite alternate;
            }
            @keyframes alarm {
                from { transform: scale(1); opacity: 0.7; }
                to { transform: scale(1.05); opacity: 1; }
            }
            .toggle-btn {
                transition: all 0.3s ease;
            }
            .connection-status {
                position: fixed;
                top: 70px;
                right: 20px;
                z-index: 40;
                padding: 4px 10px;
                border-radius: 4px;
                font-size: 12px;
                font-weight: 500;
            }
            .skeleton {
                background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
                background-size: 200% 100%;
                animation: skeleton-loading 1.5s infinite;
            }
            @keyframes skeleton-loading {
                0% { background-position: 200% 0; }
                100% { background-position: -200% 0; }
            }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen font-sans text-dark">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-sm sticky top-0 z-50 transition-all duration-300">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-graduation-cap text-primary text-2xl"></i>
                <h1 class="text-xl font-bold text-primary">智慧智慧教室监控系统 By:刘佳雨</h1>
            </div>
            
            <div class="flex items-center space-x-6">
                <div class="hidden md:flex items-center space-x-1 text-sm text-gray-600">
                    <i class="fa fa-user-circle-o"></i>
                    <span>管理员</span>
                </div>
                <div class="relative">
                    <span class="absolute -top-1 -right-1 bg-danger text-white text-xs rounded-full h-4 w-4 flex items-center justify-center">3</span>
                    <i class="fa fa-bell-o text-gray-600 hover:text-primary cursor-pointer transition-colors"></i>
                </div>
            </div>
        </div>
    </header>

    <!-- 服务器连接状态指示器 -->
    <div id="connectionStatus" class="connection-status bg-gray-200 text-gray-700">
        <i class="fa fa-circle-o-notch fa-spin mr-1"></i> 连接中...
    </div>

    <!-- 主内容区 -->
    <main class="containerainer mx-auto px-4 py-6">
        <!-- 教室信息和状态概览 -->
        <section class="mb-8">
            <div class="bg-white rounded-xl p-6 card-shadow transform transition-all duration-300 hover:shadow-lg">
                <div class="flex flex-col-col md:flex-row justify-between items-start md:items-center mb-6">
                    <div>
                        <h2 class="text-[clamp(1.25rem,3vw,1.75rem)] font-bold">BJDX - 4003教室</h2>
                        <p class="text-gray-500 text-sm mt-1">设备状态: <span class="text-success flex items-center inline-flex"><i class="fa fa-check-circle mr-1"></i> 正常运行中</span></p>
                    </div>
                    <div class="mt-4 md:mt-0 flex space-x-3">
                        <button id="refreshBtn" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg text-sm flex items-center transition-all transform hover:scale-105">
                            <i class="fa fa-refresh mr-2"></i>刷新数据
                        </button>
                        <button id="reconnectBtn" class="bg-light hover:bg-gray-200 text-dark px-4 py-2 rounded-lg text-sm flex items-center transition-all transform hover:scale-105">
                            <i class="fa fa-plug mr-2"></i>重新连接
                        </button>
                    </div>
                </div>
                
                <!-- 标语 -->
                <div class="bg-gradient-to-r from-primary/10 to-secondary/10 rounded-lg p-4 mb-6">
                    <p class="text-primary font-bold text-xl text-center md:text-left">智能监控教室环境，一键掌控舒适学习空间！</p>
                </div>
                
                <!-- 管理员信息 -->
                <div class="flex items-center mb-6">
                    <img src="https://picsum.photos/id/1005/200/200" alt="管理员照片" class="w-14 h-14 rounded-full object-cover border-2 border-primary shadow-sm">
                    <div class="ml-4">
                        <p class="font-medium">管理员：ljy</p>
                        <p class="text-sm text-gray-500">负责教室设备维护与管理</p>
                    </div>
                </div>
            </div>
        </section>

        <!-- 环境数据监测 -->
        <section class="mb-8">
            <h2 class="text-xl font-bold mb-4 flex items-center">
                <i class="fa fa-thermometer-half text-primary mr-2"></i>环境监测数据
            </h2>
            
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
                <!-- 温度卡片 -->
                <div class="bg-white rounded-xl p-5 card-shadow hover:shadow-lg transition-all border-l-4 border-warning transform hover:-translate-y-1 duration-300">
                    <div class="flex justify-between items-start">
                        <div>
                            <p class="text-gray-500 text-sm">当前温度</p>
                            <h3 class="text-3xl font-bold mt-2" id="temperature">
                                <span class="skeleton inline-block w-20 h-10 rounded"></span>
                            </h3>
                            <p class="text-sm mt-2 text-danger flex items-center">
                                <i class="fa fa-arrow-up mr-1"></i> 较昨日升高2℃
                            </p>
                        </div>
                        <div class="bg-warning/10 p-3 rounded-lg">
                            <i class="fa fa-thermometer-full text-warning text-2xl"></i>
                        </div>
                    </div>
                    <div class="mt-4 h-10">
                        <canvas id="tempChart"></canvas>
                    </div>
                </div>
                
                <!-- 湿度卡片 -->
                <div class="bg-white rounded-xl p-5 card-shadow hover:shadow-lg transition-all border-l-4 border-primary transform hover:-translate-y-1 duration-300">
                    <div class="flex justify-between items-start">
                        <div>
                            <p class="text-gray-500 text-sm">当前湿度</p>
                            <h3 class="text-3xl font-bold mt-2" id="humidity">
                                <span class="skeleton inline-block w-20 h-10 rounded"></span>
                            </h3>
                            <p class="text-sm mt-2 text-success flex items-center">
                                <i class="fa fa-arrow-down mr-1"></i> 较昨日降低5%
                            </p>
                        </div>
                        <div class="bg-primary/10 p-3 rounded-lg">
                            <i class="fa fa-tint text-primary text-2xl"></i>
                        </div>
                    </div>
                    <div class="mt-4 h-10">
                        <canvas id="humidityChart"></canvas>
                    </div>
                </div>
                
                <!-- 光照强度 -->
                <div class="bg-white rounded-xl p-5 card-shadow hover:shadow-lg transition-all border-l-4 border-secondary transform hover:-translate-y-1 duration-300">
                    <div class="flex justify-between items-start">
                        <div>
                            <p class="text-gray-500 text-sm">光照强度</p>
                            <h3 class="text-3xl font-bold mt-2" id="light">
                                <span class="skeleton inline-block w-20 h-10 rounded"></span>
                            </h3>
                            <p class="text-sm mt-2 text-gray-500 flex items-center">
                                <i class="fa fa-minus mr-1"></i> 与昨日持平
                            </p>
                        </div>
                        <div class="bg-secondary/10 p-3 rounded-lg">
                            <i class="fa fa-sun-o text-secondary text-2xl"></i>
                        </div>
                    </div>
                    <div class="mt-4 h-10">
                        <canvas id="lightChart"></canvas>
                    </div>
                </div>
                
                <!-- CO2浓度 -->
                <div class="bg-white rounded-xl p-5 card-shadow hover:shadow-lg transition-all border-l-4 border-success transform hover:-translate-y-1 duration-300">
                    <div class="flex justify-between items-start">
                        <div>
                            <p class="text-gray-500 text-sm">CO₂浓度</p>
                            <h3 class="text-3xl font-bold mt-2" id="co2Level">
                                <span class="skeleton inline-block w-20 h-10 rounded"></span>
                            </h3>
                            <p class="text-sm mt-2 text-success flex items-center">
                                <i class="fa fa-arrow-down mr-1"></i> 空气质量良好
                            </p>
                        </div>
                        <div class="bg-success/10 p-3 rounded-lg">
                            <i class="fa fa-leaf text-success text-2xl"></i>
                        </div>
                    </div>
                    <div class="mt-4 h-10">
                        <canvas id="co2Chart"></canvas>
                    </div>
                </div>
            </div>
        </section>

        <!-- 设备控制 -->
        <section class="mb-8">
            <h2 class="text-xl font-bold mb-4 flex items-center">
                <i class="fa fa-lightbulb-o text-primary mr-2"></i>设备控制
            </h2>
            
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <!-- 灯光控制 -->
                <div class="bg-white rounded-xl p-5 card-shadow hover:shadow-lg transition-all transform hover:-translate-y-1 duration-300">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="font-bold text-lg">灯光控制</h3>
                        <span id="lightStatus" class="bg-success/10 text-success text-xs px-2 py-1 rounded-full">已开启</span>
                    </div>
                    
                    <div class="flex justify-center my-6">
                        <div id="lightIndicator" class="relative w-40 h-40">
                            <div class="absolute inset-0 bg-yellow-100 rounded-full animate-pulse-slow"></div>
                            <div class="absolute inset-4 bg-yellow-300 rounded-full flex items-center justify-center">
                                <i class="fa fa-lightbulb-o text-4xl text-yellow-500"></i>
                            </div>
                        </div>
                    </div>
                    
                    <div>
                        <button id="LightOn" class="w-full bg-success hover:bg-success/90 text-white py-3 rounded-lg transition-all flex items-center justify-center text-lg toggle-btn transform hover:scale-[1.02] active:scale-[0.98]">
                            <i class="fa fa-power-off mr-2"></i>关闭灯光
                        </button>
                    </div>
                    
                    <div class="mt-4">
                        <label class="block text-sm text-gray-500 mb-2">亮度调节</label>
                        <input type="range" id="lightBrightness" min="1" max="100" value="80" class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-primary">
                    </div>
                </div>
                
                <!-- 空调控制 -->
                <div class="bg-white rounded-xl p-5 card-shadow hover:shadow-lg transition-all transform hover:-translate-y-1 duration-300">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="font-bold text-lg">空调控制</h3>
                        <span id="acStatus" class="bg-danger/10 text-danger text-xs px-2 py-1 rounded-full">已关闭</span>
                    </div>
                    
                    <div class="flex justify-center my-6">
                        <div id="acIndicator" class="relative w-40 h-40">
                            <div class="absolute inset-0 bg-blue-100 rounded-full opacity-50"></div>
                            <div class="absolute inset-4 bg-blue-300 rounded-full flex items-center justify-center">
                                <i class="fa fa-snowflake-o text-4xl text-blue-500"></i>
                            </div>
                        </div>
                    </div>
                    
                    <div>
                        <button id="SegPower" class="w-full bg-gray-200 hover:bg-gray-300 text-dark py-3 rounded-lg transition-all flex items-center justify-center text-lg toggle-btn transform hover:scale-[1.02] active:scale-[0.98]">
                            <i class="fa fa-power-off mr-2"></i>打开空调
                        </button>
                    </div>
                    
                    <div class="mt-4">
                        <label class="block text-sm text-gray-500 mb-2">温度设置</label>
                        <div class="flex items-center justify-center space-x-3">
                            <button id="SegSub" class="w-8 h-8 bg-gray-100 hover:bg-gray-200 rounded-full flex items-center justify-center transition-all transform hover:scale-110 active:scale-90">
                                <i class="fa fa-minus"></i>
                            </button>
                            <span id="segValue" class="text-xl font-bold">23℃</span>
                            <button id="SegAdd" class="w-8 h-8 bg-gray-100 hover:bg-gray-200 rounded-full flex items-center justify-center transition-all transform hover:scale-110 active:scale-90">
                                <i class="fa fa-plus"></i>
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- 报警系统 -->
                <div class="bg-white rounded-xl p-5 card-shadow hover:shadow-lg transition-all transform hover:-translate-y-1 duration-300">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="font-bold text-lg">报警系统</h3>
                        <span id="alarmStatus" class="bg-gray-100 text-gray-600 text-xs px-2 py-1 rounded-full">未触发</span>
                    </div>
                    
                    <div class="flex justify-center my-6">
                        <div id="alarmIndicator" class="relative w-40 h-40">
                            <div class="absolute inset-0 bg-gray-100 rounded-full"></div>
                            <div class="absolute inset-4 bg-gray-300 rounded-full flex items-center justify-center">
                                <i class="fa fa-bell-o text-4xl text-gray-500"></i>
                            </div>
                        </div>
                    </div>
                    
                    <div class="flex space-x-3">
                        <button id="BeepOn" class="flex-1 bg-danger hover:bg-danger/90 text-white py-3 rounded-lg transition-all flex items-center justify-center transform hover:scale-[1.02] active:scale-[0.98]">
                            <i class="fa fa-exclamation-triangle mr-2"></i>触发报警
                        </button>
                        <button id="alarmReset" class="flex-1 bg-gray-200 hover:bg-gray-300 text-dark py-3 rounded-lg transition-all flex items-center justify-center transform hover:scale-[1.02] active:scale-[0.98]">
                            <i class="fa fa-refresh mr-2"></i>重置
                        </button>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <!-- 页脚 -->
    <footer class="bg-white border-t border-gray-200 py-6 mt-12">
        <div class="container mx-auto px-4">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <p class="text-sm text-gray-500">© 2025 智慧教室监控系统 By：刘佳雨 </p>
            </div>
        </div>
    </footer>

    <script>
        // 兼容性处理
        if (!window.Promise) {
            var script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.min.js';
            document.head.appendChild(script);
        }

        function getQueryParam(param) {
            const url = window.location.href;
            const regex = new RegExp('[?&]' + param + '=([^&#]*)');
            const results = regex.exec(url);
            return results === null ? null : decodeURIComponent(results[1]) || '';
        }
        
        const deviceId = getQueryParam('did') || 'ljy';
        const clientId = 'mqttjs_' + Math.random().toString(16).substr(2, 8);
        const host = 'ws://itmojun.com:8083/mqtt';
        const options = {
            keepalive: 60,
            clientId: clientId,
            protocolId: 'MQTT',
            protocolVersion: 4,
            clean: true,
            reconnectPeriod: 1000,
            connectTimeout: 30 * 1000,
            will: {
                topic: 'WillMsg',
                payload: 'Connection Closed abnormally..!',
                qos: 0,
                retain: false
            },
        };

        // 连接 MQTT 服务器
        const client = mqtt.connect(host, options);

        // 存储历史数据用于图表展示
        const historyData = {
            temperature: [],
            humidity: [],
            light: [],
            co2Level: []
        };
        
        // 初始化图表
        function initCharts() {
            const createMiniChart = (id, color) => {
                const ctx = document.getElementById(id).getContext('2d');
                return new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: Array(8).fill(''),
                        datasets: [{
                            data: Array(8).fill(0),
                            borderColor: color,
                            backgroundColor: color + '20',
                            borderWidth: 2,
                            pointRadius: 0,
                            fill: true,
                            tension: 0.4
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: { legend: { display: false } },
                        scales: { x: { display: false }, y: { display: false } }
                    }
                });
            };
            
            return {
                tempChart: createMiniChart('tempChart', '#FF7D00'),
                humidityChart: createMiniChart('humidityChart', '#165DFF'),
                lightChart: createMiniChart('lightChart', '#36CFC9'),
                co2Chart: createMiniChart('co2Chart', '#00B42A')
            };
        }
        
        // 更新连接状态显示
        function updateConnectionStatus(status, connected) {
            const statusElement = document.getElementById('connectionStatus');
            
            if (connected) {
                statusElement.className = 'connection-status bg-success text-white';
                statusElement.innerHTML = '<i class="fa fa-check-circle mr-1"></i> 已连接';
            } else {
                statusElement.className = 'connection-status bg-danger text-white';
                statusElement.innerHTML = `<i class="fa fa-exclamation-circle mr-1"></i> ${status}`;
            }
        }
        
        // 更新历史数据和图表
        function updateHistoryData(type, value) {
            const charts = window.appCharts;
            
            if (historyData[type].length >= 8) {
                historyData[type].shift();
            }
            historyData[type].push(value);
            
            if (charts[type + 'Chart']) {
                charts[type + 'Chart'].data.datasets[0].data = historyData[type];
                charts[type + 'Chart'].update();
            }
        }

        // 连接成功处理
        client.on('connect', function() {
            console.log('Connected to MQTT server');
            updateConnectionStatus('已连接', true);

            // 订阅所有传感器主题
            client.subscribe(deviceId + '/sensor/+', function(err) {
                if (!err) {
                    console.log('已订阅传感器主题: ' + deviceId + '/sensor/+');
                }
            });
            // 订阅所有状态主题
            client.subscribe(deviceId + '/state/+', function(err) {
                if (!err) {
                    console.log('已订阅状态主题: ' + deviceId + '/state/+');
                }
            });
        });

        // 接收服务器消息
        client.on('message', function(topic, message) {
            const msg = message.toString().trim();
            console.log('Received: ' + topic + ' -> ' + msg);

            // 处理温湿度数据
            if (topic === deviceId + '/sensor/dht11') {
                const parts = msg.split('_');
                if (parts.length === 2) {
                    document.getElementById('temperature').innerText = parts[0] + ' °C';
                    document.getElementById('humidity').innerText = parts[1] + ' %RH';
                    
                    updateHistoryData('temperature', parseFloat(parts[0]));
                    updateHistoryData('humidity', parseFloat(parts[1]));
                }
            }
            // 处理光照强度数据
            else if (topic === deviceId + '/sensor/adc') {
                const lux = parseInt(msg) * 0.488;
                document.getElementById('light').innerText = lux.toFixed(1) + ' lux';
                updateHistoryData('light', lux);
            }
            // 处理CO2浓度数据
            else if (topic === deviceId + '/sensor/co2') {
                document.getElementById('co2Level').innerText = msg + ' ppm';
                updateHistoryData('co2Level', parseInt(msg));
            }
            // 处理灯光状态更新
            else if (topic === deviceId + '/state/led') {
                const lightBtn = document.getElementById('LightOn');
                const lightStatus = document.getElementById('lightStatus');
                
                if (msg === '1') {
                    lightBtn.innerHTML = '<i class="fa fa-power-off mr-2"></i>关闭灯光';
                    lightBtn.className = 'w-full bg-success hover:bg-success/90 text-white py-3 rounded-lg transition-all flex items-center justify-center text-lg toggle-btn transform hover:scale-[1.02] active:scale-[0.98]';
                    lightStatus.textContent = '已开启';
                    lightStatus.className = 'bg-success/10 text-success text-xs px-2 py-1 rounded-full';
                } else {
                    lightBtn.innerHTML = '<i class="fa fa-power-off mr-2"></i>开启灯光';
                    lightBtn.className = 'w-full bg-gray-200 hover:bg-gray-300 text-dark py-3 rounded-lg transition-all flex items-center justify-center text-lg toggle-btn transform hover:scale-[1.02] active:scale-[0.98]';
                    lightStatus.textContent = '已关闭';
                    lightStatus.className = 'bg-danger/10 text-danger text-xs px-2 py-1 rounded-full';
                }
            }
            // 处理报警状态更新
            else if (topic === deviceId + '/state/beep') {
                const beepBtn = document.getElementById('BeepOn');
                const alarmStatus = document.getElementById('alarmStatus');
                const alarmIndicator = document.getElementById('alarmIndicator').querySelector('div:first-child');
                
                if (msg === '1') {
                    beepBtn.innerHTML = '<i class="fa fa-volume-off mr-2"></i>静 音';
                    beepBtn.className = 'flex-1 bg-success hover:bg-success/90 text-white py-3 rounded-lg transition-all flex items-center justify-center transform hover:scale-[1.02] active:scale-[0.98]';
                    alarmStatus.textContent = '已触发';
                    alarmStatus.className = 'bg-danger/10 text-danger text-xs px-2 py-1 rounded-full';
                    alarmIndicator.className = 'absolute inset-0 bg-danger/20 rounded-full animate-alarm';
                } else {
                    beepBtn.innerHTML = '<i class="fa fa-exclamation-triangle mr-2"></i>触发报警';
                    beepBtn.className = 'flex-1 bg-danger hover:bg-danger/90 text-white py-3 rounded-lg transition-all flex items-center justify-center transform hover:scale-[1.02] active:scale-[0.98]';
                    alarmStatus.textContent = '未触发';
                    alarmStatus.className = 'bg-gray-100 text-gray-600 text-xs px-2 py-1 rounded-full';
                    alarmIndicator.className = 'absolute inset-0 bg-gray-100 rounded-full';
                }
            }
            // 处理空调状态更新
            else if (topic === deviceId + '/state/segPower') {
                const segPowerBtn = document.getElementById('SegPower');
                const acStatus = document.getElementById('acStatus');
                
                if (msg === '1') {
                    segPowerBtn.innerHTML = '<i class="fa fa-power-off mr-2"></i>关闭空调';
                    segPowerBtn.className = 'w-full bg-primary hover:bg-primary/90 text-white py-3 rounded-lg transition-all flex items-center justify-center text-lg toggle-btn transform hover:scale-[1.02] active:scale-[0.98]';
                    acStatus.textContent = '已开启';
                    acStatus.className = 'bg-success/10 text-success text-xs px-2 py-1 rounded-full';
                } else {
                    segPowerBtn.innerHTML = '<i class="fa fa-power-off mr-2"></i>打开空调';
                    segPowerBtn.className = 'w-full bg-gray-200 hover:bg-gray-300 text-dark py-3 rounded-lg transition-all flex items-center justify-center text-lg toggle-btn transform hover:scale-[1.02] active:scale-[0.98]';
                    acStatus.textContent = '已关闭';
                    acStatus.className = 'bg-danger/10 text-danger text-xs px-2 py-1 rounded-full';
                }
            }
            // 处理空调温度更新
            else if (topic === deviceId + '/state/seg') {
                document.getElementById('segValue').innerText = msg + '℃';
            }
        });

        // 灯光控制按钮事件
        document.getElementById('LightOn').addEventListener('click', function() {
            const message = this.innerText.includes('开') ? 'a' : 'b';
            const action = this.innerText.includes('开') ? '开启' : '关闭';
            client.publish(deviceId + '/cmd', message);
            console.log(`发送${action}灯光命令: ${message}`);
        });

        // 报警控制按钮事件
        document.getElementById('BeepOn').addEventListener('click', function() {
            const message = this.innerText.includes('报') ? 'c' : 'd';
            const action = this.innerText.includes('报') ? '触发' : '关闭';
            client.publish(deviceId + '/cmd', message);
            console.log(`发送${action}报警命令: ${message}`);
        });
        
        // 报警重置按钮
        document.getElementById('alarmReset').addEventListener('click', function() {
            client.publish(deviceId + '/cmd', 'd');
        });
        
        // 空调电源控制
        document.getElementById('SegPower').addEventListener('click', function() {
            const message = this.innerText.includes('打开') ? 'f' : 'g';
            const action = this.innerText.includes('打开') ? '打开' : '关闭';
            client.publish(deviceId + '/cmd', message);
            console.log(`发送${action}空调命令: ${message}`);
        });
        
        // 空调温度加一
        document.getElementById('SegAdd').addEventListener('click', function() {
            client.publish(deviceId + '/cmd', 'h');
            console.log('发送空调温度加一命令');
        });
        
        // 空调温度减一
        document.getElementById('SegSub').addEventListener('click', function() {
            client.publish(deviceId + '/cmd', 'j');
            console.log('发送空调温度减一命令');
        });
        
        // 亮度调节
        document.getElementById('lightBrightness').addEventListener('change', function() {
            client.publish(deviceId + '/cmd', `brightness:${this.value}`);
            console.log(`发送亮度调节命令: ${this.value}`);
        });
        
        // 重新连接按钮
        document.getElementById('reconnectBtn').addEventListener('click', function() {
            if (client) {
                client.end();
            }
            setTimeout(() => {
                window.location.reload();
            }, 1000);
        });
        
        // 刷新按钮
        document.getElementById('refreshBtn').addEventListener('click', function() {
            this.innerHTML = '<i class="fa fa-refresh fa-spin mr-2"></i>刷新中...';
            this.disabled = true;
            client.publish(deviceId + '/cmd', 'refresh');
            
            setTimeout(() => {
                this.innerHTML = '<i class="fa fa-refresh mr-2"></i>刷新数据';
                this.disabled = false;
            }, 1000);
        });
        
        // 连接错误处理
        client.on('error', function(error) {
            console.error('MQTT连接错误:', error);
            updateConnectionStatus('连接错误', false);
        });
        
        // 连接断开处理
        client.on('close', function() {
            console.log('MQTT连接已断开');
            updateConnectionStatus('连接已断开', false);
        });
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            window.appCharts = initCharts();
            
            // 为老旧浏览器提供支持
            if (!Array.prototype.includes) {
                Array.prototype.includes = function(searchElement) {
                    return this.indexOf(searchElement) !== -1;
                };
            }
            
            // 设置默认数据
            setTimeout(() => {
                const tempEl = document.getElementById('temperature');
                const humidityEl = document.getElementById('humidity');
                const lightEl = document.getElementById('light');
                const co2El = document.getElementById('co2Level');
                
                if (tempEl.innerHTML.includes('skeleton')) {
                    tempEl.innerHTML = '25.5 °C';
                    humidityEl.innerHTML = '45 %RH';
                    lightEl.innerHTML = '320 lux';
                    co2El.innerHTML = '680 ppm';
                    
                    updateHistoryData('temperature', 25.5);
                    updateHistoryData('humidity', 45);
                    updateHistoryData('light', 320);
                    updateHistoryData('co2Level', 680);
                }
            }, 3000);
        });
    </script>
</body>
</html>
